package controller

import (
	"fmt"
	"fx_swift_ifcgate/api"
	"fx_swift_ifcgate/internal/service"
	"fx_swift_ifcgate/pkg/code"
	"fx_swift_ifcgate/pkg/fileutils"
	"fx_swift_ifcgate/pkg/global"
	"fx_swift_ifcgate/pkg/internalerrors"
	"fx_swift_ifcgate/pkg/logger"
	"fx_swift_ifcgate/pkg/upload"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"strings"
)

// 商户入网
func MerChantOnboard(c *gin.Context) {
	req := &api.MerChantVAReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	err := service.NewMerchantVASrv().MerChantOnboard(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, nil)
	}
}

// KYC认证资料保存
func CreateMerChantTemp(c *gin.Context) {
	req := &api.MerChantTempReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}

	err := service.NewMerchantVASrv().CreateMerChantTemp(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, nil)
	}
}

// 获取KYC认证资料
func GetMerChantTemp(c *gin.Context) {
	//req := &api.MerChantTempReq{}
	//if err := c.ShouldBindJSON(&req); err != nil {
	//	code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
	//	return
	//}

	result, err := service.NewMerchantVASrv().GetMerChantTemp(c, "")
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 根据业务性质类型获取业务性质
func QueryBusinessNature(c *gin.Context) {
	natureType := c.Query("natureType")
	result, err := service.NewMerchantVASrv().QueryBusinessNature(c, natureType)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 获取资金来源
func QuerySourceFund(c *gin.Context) {
	result, err := service.NewMerchantVASrv().QuerySourceFund(c)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 获取付款目的
func QueryPaymentPurpose(c *gin.Context) {
	result, err := service.NewMerchantVASrv().QueryPaymentPurpose(c)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 获取营业额
func QueryTurnover(c *gin.Context) {
	//result, err := enum.InitTurnover()
	result, err := service.NewMerchantVASrv().QueryTurnover(c)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 获取交易量
func QueryTransaction(c *gin.Context) {
	//result, err := enum.InitTransaction()
	result, err := service.NewMerchantVASrv().QueryTransaction(c)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 文件上传至S3以及sftp
func UpLoadFiles(c *gin.Context) {
	var (
		result []string
		err    error
	)
	s3OrAliYun := global.ViperObj.GetString("sftp.uploadFlag")
	if s3OrAliYun == "s3" {
		result, err = upload.UploadFile(c)
	} else {
		result, err = upload.BatchUploadFile(c)
	}

	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	}
	if result == nil {
		return
	}

	fmt.Println("待上传文件列表：", strings.Join(result, ","))

	sftpUtil := fileutils.SFTPUtil{}
	host := global.ViperObj.GetString("sftp.host")
	port := global.ViperObj.GetInt("sftp.port")
	user := global.ViperObj.GetString("sftp.user")
	psw := global.ViperObj.GetString("sftp.password")
	sftp := sftpUtil.NewSFTPUtil(host, port, user, psw)

	//检查目录是否已存在，不存在则创建
	targetPath := global.ViperObj.GetString("sftp.targetPath")
	err = sftp.CreateDirIfNotExist(targetPath)
	if err != nil {
		logger.SugarLogger.Error(err)
		return
	}

	for _, value := range result {
		if !strings.Contains(value, "http") {
			value = "https://" + value
		}
		resp, err := http.Get(value)
		if err != nil {
			logger.SugarLogger.Error("无法获取文件: ", err)
			return
		}
		defer resp.Body.Close()

		// 读取文件数据
		data, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.SugarLogger.Error("无法读取文件数据: ", err)
			return
		}

		err = sftp.UploadFileToSFTP(data, targetPath+"/"+strings.Split(value, "/")[len(strings.Split(value, "/"))-1])
		if err != nil {
			code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
			return
		}
	}
	code.Success(c, gin.H{
		"files": result,
	})
}

// 获取账户持有人名称
func GetMerChantName(c *gin.Context) {
	result, err := service.NewMerchantVASrv().GetMerChantName(c)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 获取当前商户入网状态信息
func QueryMerChantMessage(c *gin.Context) {
	result, err := service.NewMerchantVASrv().QueryMerChantMessage(c)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}
